@file:Suppress("unused")

package com.ljj.bitetime.item

import android.os.Parcel
import android.os.Parcelable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableDoubleStateOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.setValue

/**
 * 购物车类
 */
class Cart() : Parcelable {
    companion object {
        const val TAG = "BiteTime.Cart"

        @JvmField
        val CREATOR = object : Parcelable.Creator<Cart> {
            override fun createFromParcel(parcel: Parcel): Cart {
                return Cart(parcel)
            }

            override fun newArray(size: Int): Array<Cart?> {
                return arrayOfNulls(size)
            }
        }
    }
    private var parcelableItems: Map<Dish, Int> = emptyMap()
    private var parcelableTotalPrice: Double = 0.0
    val items = mutableStateMapOf<Dish, Int>()
    var totalPrice by mutableDoubleStateOf(0.0)

    private constructor(parcel: Parcel) : this() {
        val dishList = parcel.createTypedArrayList(Dish.CREATOR) ?: emptyList()
        val quantities = parcel.createIntArray() ?: IntArray(0)
        for (i in dishList.indices) {
            if (i < quantities.size) {
                items[dishList[i]] = quantities[i]
            }
        }
        totalPrice = parcel.readDouble()
        updateParcelableState()
    }

    override fun describeContents(): Int = 0

    override fun writeToParcel(dest: Parcel, flags: Int) {
        updateParcelableState()
        dest.writeTypedList(parcelableItems.keys.toList())
        dest.writeIntArray(parcelableItems.values.toIntArray())
        dest.writeDouble(parcelableTotalPrice)
    }

    override fun toString(): String {
        return "Cart(items=${items.toMap()}, totalPrice=$totalPrice)"
    }

    /**
     * 更新用于序列化的 backing property
     */
    private fun updateParcelableState() {
        parcelableItems = items.toMap()
        parcelableTotalPrice = totalPrice
    }

    /* 操作方法 */
    /**
     * 添加菜品到购物车
     * @param dish 要添加的菜品
     * @param quantity 数量
     */
    fun addItem(dish: Dish, quantity: Int = 1) {
        if (quantity <= 0) return
        items[dish] = (items[dish] ?: 0) + quantity
        recalculateTotal()
        updateParcelableState()
    }

    /**
     * 减少菜品数量
     * @param dish 要减少的菜品
     * @param quantity 数量
     */
    fun reduceItem(dish: Dish, quantity: Int = 1) {
        if (quantity <= 0) return
        val currentQuantity = items[dish] ?: 0
        if (currentQuantity - quantity <= 0) {
            items.remove(dish)
        } else {
            items[dish] = currentQuantity - quantity
        }
        recalculateTotal()
        updateParcelableState()
    }

    /**
     * 从购物车移除菜品
     * @param dish 要移除的菜品
     */
    fun removeItem(dish: Dish) {
        items.remove(dish)
        recalculateTotal()
        updateParcelableState()
    }

    /**
     * 清空购物车
     */
    fun clear() {
        items.clear()
        totalPrice = 0.0
        updateParcelableState()
    }

    /* 访问方法 */
    /**
     * 获取购物车中某菜品的数量
     * @param dish 要查询的菜品
     * @return 菜品数量
     */
    fun getItemQuantity(dish: Dish): Int = items[dish] ?: 0

    /**
     * 获取购物车中所有菜品的数量
     * @return 菜品数量
     */
    fun getTotalQuantity(): Int = items.values.sum()

    /* 其他方法 */
    /**
     * 重新计算总价
     */
    private fun recalculateTotal() {
        totalPrice = items.entries.sumOf { (dish, quantity) ->
            calculateDishTotalPrice(dish) * quantity
        }
    }

    /**
     * 计算单个菜品的总价（包含选项价格）
     * @param dish 要计算价格的菜品
     * @return 菜品总价
     */
    private fun calculateDishTotalPrice(dish: Dish): Double {
        var price = dish.basePrice
        // 添加分量额外价格
        val options = dish.options
        options.portionSize?.let {
            price += it.extraPrice
        }
        // 添加加料额外价格
        options.toppings?.forEach { topping ->
            price += topping.extraPrice
        }
        return price
    }
}